// 文件位置: src/main/java/com/pharmacy/LogManage/controller/OperationLogController.java
package com.pharmacy.LogManage.controller;

import com.pharmacy.LogManage.entity.OperationLog;
import com.pharmacy.LogManage.service.OperationLogService;
import com.pharmacy.UserManage.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/logs")
public class OperationLogController {

    @Autowired
    private OperationLogService operationLogService;

    // 获取所有操作日志（需要管理员权限）
    @GetMapping("/all")
    public ResponseEntity<Map<String, Object>> getAllLogs(HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        User currentUser = (User) session.getAttribute("currentUser");

        if (currentUser == null || !"admin".equals(currentUser.getRole())) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.status(403).body(response);
        }

        try {
            List<OperationLog> logs = operationLogService.getAllLogs();
            response.put("success", true);
            response.put("data", logs);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取操作日志失败");
            return ResponseEntity.status(500).body(response);
        }
    }

    // 按日期范围查询操作日志（需要管理员权限）
    @GetMapping("/date-range")
    public ResponseEntity<Map<String, Object>> getLogsByDateRange(
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate,
            HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        User currentUser = (User) session.getAttribute("currentUser");

        if (currentUser == null || !"admin".equals(currentUser.getRole())) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.status(403).body(response);
        }

        try {
            List<OperationLog> logs = operationLogService.getLogsByDateRange(startDate, endDate);
            response.put("success", true);
            response.put("data", logs);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取操作日志失败");
            return ResponseEntity.status(500).body(response);
        }
    }

    // 按用户ID查询操作日志（需要管理员权限）
    @GetMapping("/user/{userId}")
    public ResponseEntity<Map<String, Object>> getLogsByUserId(@PathVariable Integer userId, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        User currentUser = (User) session.getAttribute("currentUser");

        if (currentUser == null || !"admin".equals(currentUser.getRole())) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.status(403).body(response);
        }

        try {
            List<OperationLog> logs = operationLogService.getLogsByUserId(userId);
            response.put("success", true);
            response.put("data", logs);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取操作日志失败");
            return ResponseEntity.status(500).body(response);
        }
    }

    // 按操作类型查询操作日志（需要管理员权限）
    @GetMapping("/operation-type/{operationType}")
    public ResponseEntity<Map<String, Object>> getLogsByOperationType(
            @PathVariable String operationType, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        User currentUser = (User) session.getAttribute("currentUser");

        if (currentUser == null || !"admin".equals(currentUser.getRole())) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.status(403).body(response);
        }

        try {
            List<OperationLog> logs = operationLogService.getLogsByOperationType(operationType);
            response.put("success", true);
            response.put("data", logs);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取操作日志失败");
            return ResponseEntity.status(500).body(response);
        }
    }


    // 获取当前用户自己的操作日志
    @GetMapping("/my")
    public ResponseEntity<Map<String, Object>> getMyLogs(HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        User currentUser = (User) session.getAttribute("currentUser");

        if (currentUser == null) {
            response.put("success", false);
            response.put("message", "未登录");
            return ResponseEntity.status(401).body(response);
        }

        try {
            List<OperationLog> logs = operationLogService.getLogsByUserId(currentUser.getId());
            response.put("success", true);
            response.put("data", logs);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取操作日志失败");
            return ResponseEntity.status(500).body(response);
        }
    }
    // 在OperationLogController中添加以下方法

    // 删除单条操作日志（需要管理员权限）
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteLog(@PathVariable Integer id, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        User currentUser = (User) session.getAttribute("currentUser");

        if (currentUser == null || !"admin".equals(currentUser.getRole())) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.status(403).body(response);
        }

        try {
            boolean deleted = operationLogService.deleteLog(id);
            if (deleted) {
                response.put("success", true);
                response.put("message", "删除成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "日志不存在");
                return ResponseEntity.status(404).body(response);
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "删除日志失败");
            return ResponseEntity.status(500).body(response);
        }
    }

    // 清空所有操作日志（需要管理员权限）
    @DeleteMapping("/clear")
    public ResponseEntity<Map<String, Object>> clearLogs(HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        User currentUser = (User) session.getAttribute("currentUser");

        if (currentUser == null || !"admin".equals(currentUser.getRole())) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.status(403).body(response);
        }

        try {
            operationLogService.clearLogs();
            response.put("success", true);
            response.put("message", "清空日志成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "清空日志失败");
            return ResponseEntity.status(500).body(response);
        }
    }
}